#!/usr/bin/env python
#coding=utf-8
import multiprocessing,paramiko
import time,os,sys
import db_connect
from umwork.models import * 


ip_list = sys.argv[1]
cmd = sys.argv[2]

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

Date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
Time = time.strftime('%H:%M:%S',time.localtime(time.time()))
with open('result.txt','w') as f:
    f.write('----------%s %s----------\n'%(Date,Time))

def run(ip,user,port,passwd,cmd):
    client.connect(ip,int(port),user,passwd,timeout=5)
    stdin, stdout, stderr = client.exec_command(cmd)
    Result = stdout.read(),stderr.read()
    with open('result.txt','a') as f:
        f.write('\n\n### %s 执行结果：### \n'%ip)
    for i in Result:
        with open('result.txt','a') as f:
            f.write(i)
    
p=multiprocessing.Pool(len(ip_list.split()))
result= []
for ip in ip_list.split():
    user = IP.objects.get(ip = ip).user
    passwd = IP.objects.get(ip = ip).passwd
    port = IP.objects.get(ip = ip).port
    result.append(p.apply_async(run,(ip,user,port,passwd,cmd)))
p.close()
p.join()

for r in result:
    r.get()